package com.lj.tools.jwt;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;

@Data
public class JwtToken {

    private String key = "jwt@123456";
    private int expiredTime = 30;//30分钟
    private int refreshTime = 10;//10分钟刷新


    public static JwtToken newInstance(){
        return new JwtToken();
    }

    public String apiToken(String id){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, expiredTime);

        Algorithm algorithm = Algorithm.HMAC512(key);
        String token =  JWT.create().withIssuer("lj")
                .withIssuedAt(new Date())
                .withClaim("id", id)
                .withExpiresAt(calendar.getTime())
                .sign(algorithm);
        return token;
    }


    public String userId(String token){
        if (!StringUtils.hasLength(token)){
            return null;
        }
        Algorithm algorithm = Algorithm.HMAC512(key);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer("lj").build();
        DecodedJWT jwt = verifier.verify(token);
        return jwt.getClaim("id").asString();
    }

    //检查快过期了
    public String refreshToken(String token){
        DecodedJWT jwt = JWT.decode(token);
        return apiToken(jwt.getClaim("id").asString());
    }

}
